package com.itheima.my_reggie.web;

import com.itheima.my_reggie.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

//    @Value("${reggie.path}")
    @PostMapping("/upload")
    public Result uploadImg(MultipartFile file) throws IOException {
//      获取上传图片的名称
        String originalFilename = file.getOriginalFilename();
//      截取名称中最后以"."结尾的后缀
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
//      给图片重新生成UUID+后缀的名称
        String fileName= UUID.randomUUID().toString()+substring;
//      将上传的图片存储至本地
        file.transferTo(new File("E://JavaProject//Project//imgs//"+fileName));
//      创建一个目录对象
//      File dir = new File(basePath);
//      判断当前目录是否存在
//        if(!dir.exists()){
//            //目录不存在，需要创建
//            dir.mkdirs();
//        }
//            //将临时文件转存到指定位置
//            file.transferTo(new File(basePath + fileName));
        return Result.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {
        IOUtils.copy(new FileInputStream("E://JavaProject//Project//imgs//"+name),response.getOutputStream());
    }
}
